<?php

require_once 'dbutils.php';
require_once 'RestUtils.php';
require_once 'Base.php';

class UserMessages extends Base
{

    function GET($matches)
    {
        $req = RestUtils::processRequest('GET');
        $req_vars = $req->getRequestVars();
        $db_vars = dbutils::translate_rest_params($req_vars);
        $res = $this->selectUserMessages($db_vars);
        if ($res['code'] == 0)
            RestUtils::sendResponse(200, $res['result'], 'application/json');
        else
            RestUtils::sendResponse(404, dbutils::error_to_json($res['code'], $res['message']), 'application/json');
    }

    function POST($matches)
    {
        $req = RestUtils::processRequest('POST');
        $req_vars = $req->getRequestVars();
        $db_vars = dbutils::translate_rest_params($req_vars);
        $res = $this->insertUserMessage($db_vars);
        if ($res['code'] == 0)
            RestUtils::sendResponse(200, $res['result'], 'application/json');
        else
            RestUtils::sendResponse(404, dbutils::error_to_json($res['code'], $res['message']), 'application/json');
    }

    /*    function PUT($matches) {
        $req = RestUtils::processRequest('PUT');
        $req_vars = $req->getRequestVars();
        $db_vars = dbutils::translate_rest_params($req_vars);
        $res = $this->updateUserJourney($db_vars);
        if ($res['code'] == 0)
            RestUtils::sendResponse(200);
        else
            RestUtils::sendResponse(404, dbutils::error_to_json($res['code'], $res['message']), 'application/json');
    }*/
    function DELETE($matches)
    {
        $req = RestUtils::processRequest('DELETE');
        $req_vars = $req->getRequestVars();
        $db_vars = dbutils::translate_rest_params($req_vars);
        $res = $this->deleteUserMessages($db_vars);
        if ($res['code'] == 0)
            RestUtils::sendResponse(200);
        else
            RestUtils::sendResponse(404, dbutils::error_to_json($res['code'], $res['message']), 'application/json');
    }

    private function selectUserMessages($values)
    {
        $code = 0;
        $msg = '';
        $result = null;
        try {
            if (!$values)
                return array('code' => -1, 'message' => 'required request parameters not found', 'result' => null);

            if (!array_key_exists('id_user', $values))
                return array('code' => -1, 'message' => 'required request parameters not found', 'result' => null);

            $db_handle = @pg_pconnect(dbutils::$conn_string);

            $query = "SELECT m.id AS id_message,
                             m.id_journey,
                             m.id_sender,
                             m.datetime,
                             m.title,
                             m.body,
                             uj.fl_owner
                      FROM user_journeys uj, messages m
                      WHERE m.id_recipient = {$values['id_user']}
                      AND uj.id_user = m.id_recipient
                      AND uj.id_journey = m.id_journey";

            if (array_key_exists('fl_owner', $values))
                $query .= " AND uj.fl_owner = '{$values['fl_owner']}'";

            $result = @pg_query($db_handle, $query);
            if ($result)
                $result = dbutils::dbresult_to_json($result);
            else {
                $code = -1;
                $msg = 'no db records found ' . @pg_last_error($db_handle);
            }
            @pg_close($db_handle);
        } catch (Exception $e) {
            $code = $e->getCode();
            $msg = $e->getMessage();
        }
        return array('code' => $code, 'message' => $msg, 'result' => $result);
    }

    private function insertUserMessage($values)
    {
        $code = 0;
        $msg = '';
        $result = null;
        try {
            if (!$values)
                return array('code' => -1, 'message' => 'required request parameters not found', 'result' => null);

            if (!array_key_exists('title', $values)
                || !array_key_exists('body', $values)
                || !array_key_exists('id_journey', $values)
                || !array_key_exists('id_sender', $values)
                || !array_key_exists('id_recipient', $values)
            )
                return array('code' => -1, 'message' => 'required request parameters not found', 'result' => null);

            $db_handle = @pg_pconnect(dbutils::$conn_string);

            $res = @pg_query($db_handle, "SELECT j.status
                                            FROM journeys j
                                            WHERE j.id = {$values['id_journey']}");
            if ($res && @pg_num_rows($res) > 0) {
                $row = @pg_fetch_array($res, 0);
                if (strcasecmp($row['status'], 'CLOSE') != 0) {

                    $res = @pg_query($db_handle, "SELECT nextval('messages_id_seq') as key");
                    if ($res) {
                        $row = @pg_fetch_array($res, 0);
                        $id_message = $row['key'];
                    }

                    if ($id_message) {
                        $insert = "INSERT INTO messages (id, title, body,
                                            datetime, id_journey, id_sender,
                                            id_recipient)
                                    VALUES ({$id_message}, '{$values['title']}',
                                            '{$values['body']}', LOCALTIMESTAMP(0),
                                            {$values['id_journey']},
                                            {$values['id_sender']}, {$values['id_recipient']})";

                        $result = @pg_query($db_handle, $insert);
                        if ($result) {
                            $now = date('Y-m-d H:i:s');
                            $result = json_encode(array('idMessage' => $id_message, 'datetime' => "{$now}"));
                        }
                        else {
                            $code = -1;
                            $msg = 'inserting records not possible ' . @pg_last_error($db_handle);
                        }
                    } else {
                        $code = -1;
                        $msg = 'error generating idMessage ' . @pg_last_error($db_handle);
                    }
                } else {
                    $code = -2;
                    $msg = 'the journey is close';
                }
            } else {
                $code = -2;
                $msg = 'the journey does not exists';
            }
            @pg_close($db_handle);
        } catch (Exception $e) {
            $code = $e->getCode();
            $msg = $e->getMessage();
        }
        return array('code' => $code, 'message' => $msg, 'result' => $result);
    }

    private function deleteUserMessages($values)
    {
        $code = 0;
        $msg = '';
        $result = null;
        try {
            if (!$values)
                return array('code' => -1, 'message' => 'required request parameters not found', 'result' => null);

            $delete = "";
            foreach ($values as $val) {
                if (!array_key_exists('id_message', $val))
                    return array('code' => -1, 'message' => 'required request parameters not found', 'result' => null);

                $delete .= "DELETE FROM messages
                               WHERE id={$val['id_message']};";
            }
            $db_handle = @pg_pconnect(dbutils::$conn_string);

            $result = @pg_query($db_handle, $delete);
            if (!$result) {
                $code = -1;
                $msg = 'deleting records not possible ' . @pg_last_error($db_handle);
            }
            @pg_close($db_handle);
        } catch (Exception $e) {
            $code = $e->getCode();
            $msg = $e->getMessage();
        }
        return array('code' => $code, 'message' => $msg, 'result' => $result);
    }
}

?>